﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for FundJob
/// </summary>
public class FundJob
{
	public FundJob()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    private readonly object syncLock = new object();

    public void generateFundPriceJob()
    {
        new FundSource().checkDailyPrice();
    }

    public void autoPayment()
    {
        DataTable dt = DBManager.GetData("select policy_no FROM R_POLICY P where P.payment_method='Auto' and status='ACTIVE'");
        if (dt != null)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                String policyNo = (String)dt.Rows[i][0];
                Policy policy = Policy.getPolicy(policyNo);

                DataTable lastPayDayDt = DBManager.GetData("select Max(P.payment_datetime) last_pay_day FROM R_PAYMENT P where P.type = 'PREMIUM' and policy_no='" + policyNo + "'");
                
                DateTime shouldPayDay = DateTime.Now;
                if (lastPayDayDt != null && lastPayDayDt.Rows.Count>0)
                {
                    //DateTime lastPayDay = (DateTime)lastPayDayDt.Rows[0][0];
                   // DateTime lastPayDay = DateTime.ParseExact(lastPayDayDt.Rows[0][0].ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
                    DateTime lastPayDay = lastPayDayDt.Rows[0].Field<DateTime?>("last_pay_day")??DateTime.Now; 

                    if (policy.premiumFrequency == "M")
                    {
                        shouldPayDay = lastPayDay.AddMonths(1);
                    }
                    else
                    {
                        shouldPayDay = lastPayDay.AddYears(1);
                    }
                }

                if (shouldPayDay.Year == DateTime.Now.Year && shouldPayDay.Month == DateTime.Now.Month && shouldPayDay.Day == DateTime.Now.Day)
                {
                    PolicyRules policyRules = new PolicyRules();
                    policyRules.payPremium(policy.accountId,policy.policyNo);
                   // Alert.sendAlert(policy.userId, "PAYMENT", "Premium Paid", "");
                }
            }
        }

    }


    public void runAllJobs(){
        lock (syncLock) { 
            FundJob job = new FundJob();
            job.generateFundPriceJob();
            //job.autoPayment();
        }
    }
 
}